<?php

require_once 'smarty/Smarty.class.php';

class Page {

    protected $allowedUsers = array('STUDENT');
    protected $compatibilityMode = false;
    protected $title = "";
    protected $smarty;
    protected $template;
    protected $customTemplate = false;

    public function __construct() {
        $this->smarty = new Smarty();
        $this->smarty->assign('user', App::getActiveUser());
        $this->smarty->assign('page', $this);
        $this->smarty->assign('pageStyles', array());
        $this->smarty->assign('contentTemplate', $this->template);
    }

    public function display() {
        if (!$this->compatibilityMode) {
            header('Content-Type: application/xhtml+xml');
        }
        $this->loadUserInfo();
        echo $this->getContent();
    }

    public function getContent() {
        return $this->smarty->fetch($this->customTemplate ? $this->template : 'page.tpl');
    }

    public function checkPermissions() {
        if (empty($this->allowedUsers)) {
            return true;
        }
        $user = App::getActiveUser();
        if ($user !== null) {
            $p = $user->getPermissions();
            foreach ($this->allowedUsers as $permission) {
                if (in_array($permission,$p)) {
                    return true;
                }
            }
            return false;
        } else {
            return false;
        }
    }

    public function getTitle() {
        return $this->title;
    }

    protected function loadUserInfo() {
        if (App::getActiveUser() == null) {
            return;
        }
        $id = App::getActiveUser()->getId();

        $sql = " SELECT U.Username, U.Permissions, UI.Name AS UIName, UI.Semester, S.Name AS SName, L.Language, G.GroupNumber FROM " .
                        Dal::USER_TABLE . " U INNER JOIN " .
                        Dal::INFO_TABLE . " UI ON UI.UserId = U.Id INNER JOIN " .
                        Dal::SPEC_TABLE . " S ON UI.SpecId = S.Id INNER JOIN " .
                        Dal::LANG_TABLE . " L ON UI.LangId = L.Id INNER JOIN " .
                        Dal::GROUP_TABLE . " G ON UI.CsopId = G.Id " .
                        " WHERE U.Id = {$id} ";

        $userinfo = Dal::fetchAll($sql);
        $this->smarty->assign('userinfo', $userinfo[0]);
    }

}

?>